package com.jielin.handling.service.unit.impl;

import com.alibaba.fastjson.JSON;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.record.*;
import com.jielin.handling.entity.role.Role;
import com.jielin.handling.entity.role.UserRole;
import com.jielin.handling.mapper.accesspath.AccessPathMapper;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.record.RecordAnswerMapper;
import com.jielin.handling.mapper.record.RecordCommonalityModelMapper;
import com.jielin.handling.mapper.record.RecordQuestionMapper;
import com.jielin.handling.mapper.record.RecordTypeModelMapper;
import com.jielin.handling.mapper.role.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jielin.handling.entity.unit.Organization;
import com.jielin.handling.mapper.unit.UnitMapper;
import com.jielin.handling.service.unit.UnitService;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wr
 * @date 2019/5/7 - 19:27
 */
@Service
@Slf4j
public class UnitServiceImpl implements UnitService {
    @Autowired
    private UnitMapper unitMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PoliceManMapper policeManMapper;
    @Autowired
    private AccessPathMapper accessPathMapper;
    @Autowired
    private RecordTypeModelMapper recordTypeModelMapper;
    @Autowired
    private RecordCommonalityModelMapper recordCommonalityModelMapper;
    @Autowired
    private RecordQuestionMapper recordQuestionMapper;
    @Autowired
    private RecordAnswerMapper recordAnswerMapper;

    @Override
    public Organization findUnitInfoById(String organizationId) {
        if (StringUtil.isEmpty(organizationId)) {
            return null;
        }
        // 查询本单位信息
        return unitMapper.findUnitInfoById(organizationId);
    }

    @Override
    public Boolean findChildUnitNumById(String id) {
        if (StringUtil.isEmpty(id)) {
            return false;
        }
        return unitMapper.findChildUnitNumById(id) > 0;
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int addUnitInfo(Organization organization) {
        if (organization == null) {
            return -1;
        }
        int flag = -1;
        try {
            // 修改单位为不是新增单位
            organization.setIsNew("0");
            unitMapper.updateUnitIsNew(organization);
            PoliceMan pm = new PoliceMan();
            pm.setId(StringUtil.generatorUUID());
            pm.setName(organization.getOrganizationName());
            pm.setPassword("88888888");
            pm.setOrganizationid(organization.getId());
            pm.setUsername(organization.getHandleUnitCode());
            pm.setPoliceCode(organization.getHandleUnitCode());
            log.info("addUnitInfo===>添加用户账户信息PoliceMan:" + JSON.toJSONString(pm));
            policeManMapper.addPoliceManInfo(pm);
            Role role = new Role();
            role.setId(StringUtil.generatorUUID());
            role.setOrganizationId(organization.getId());
            role.setRoleName("单位管理员");
            role.setWeights(2);
            log.info("addUnitInfo===>添加用户角色信息Role:" + JSON.toJSONString(role));
            roleMapper.addRoleInfo(role);
            UserRole userRole = new UserRole();
            userRole.setId(StringUtil.generatorUUID());
            userRole.setPoliceId(pm.getId());
            userRole.setRoleId(role.getId());
            log.info("addUnitInfo===>添加用户与关联角色信息UserRole:" + JSON.toJSONString(userRole));
            roleMapper.addPoliceRoleInfo(userRole);
            // 获取所有路径信息的id
            List<String> allAccessPathIdList = accessPathMapper.findAllPathId();
            log.info("addUnitInfo===>添加权限给当前角色RolePower：RoleId:" + role.getId());
            accessPathMapper.addPowerPathByRoleId(role.getId(), allAccessPathIdList);

            log.info("addUnitInfo===>添加笔录模板信息给当前单位");
            List<RecordTypeModel> rmList = new ArrayList<>();
            List<RecordCommonalityModel> rcmList = new ArrayList<>();
            List<RecordQuestion> rqList = new ArrayList<>();
            List<RecordAnswer> raList = new ArrayList<>();
            // 获取标准笔录模板数据
            List<RecordTypeModelNormal> list = recordTypeModelMapper.findNormalModel();
            for (RecordTypeModelNormal rtmn : list) {
                RecordTypeModel rtm = RecordTypeModel.builder().id(StringUtil.generatorUUID())
                        .modelname(rtmn.getModelName()).iconPath(rtmn.getIconPath()).orgId(organization.getId())
                        .build();
                List<RecordCommonalityModel> beforeRcmList = recordCommonalityModelMapper
                        .findCommonalityByModelId(rtmn.getModelId(), "");
                for (RecordCommonalityModel beforeRcm : beforeRcmList) {
                    List<RecordQuestion> beforeRqList = recordQuestionMapper.findQuestionByModelId(beforeRcm.getId());
                    beforeRcm.setId(StringUtil.generatorUUID());
                    beforeRcm.setModeltypeid(rtm.getId());
                    for (RecordQuestion beforeRq : beforeRqList) {
                        List<RecordAnswer> beforeRaList = recordAnswerMapper.findAnswerByQuestionId(beforeRq.getId());
                        beforeRq.setId(StringUtil.generatorUUID());
                        beforeRq.setModelid(beforeRcm.getId());
                        for (RecordAnswer beforeRa : beforeRaList) {
                            beforeRa.setId(StringUtil.generatorUUID());
                            beforeRa.setQuestionid(beforeRq.getId());
                            raList.add(beforeRa);
                        }
                        rqList.add(beforeRq);
                    }
                    rcmList.add(beforeRcm);
                }
                rmList.add(rtm);
            }
            recordTypeModelMapper.addModelS(rmList);
            recordCommonalityModelMapper.addMyModelS(rcmList);
            recordQuestionMapper.addQuestionS(rqList);
            recordAnswerMapper.addAnswerS(raList);
            flag = 1;
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        log.info("service 事务end...");
        return flag;
    }

    @Override
    public Map<String, Object> findRegistrationCode(String unitCode) {
        //查询注册码是否过期
        Map<String, Object> map =unitMapper.findRegistrationCode(unitCode);
        return null;
    }

}
